package com.itheima.reggie.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String path;

    /**
     * 图片上传接口
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R upload(MultipartFile file) {
        //获取原始文件名
        String filename = file.getOriginalFilename();
        //获取文件后缀名
        String suffixName = filename.substring(filename.lastIndexOf("."));
        filename = UUID.randomUUID().toString() + suffixName;

        //判断文件夹是否存在,不存在则创建
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        //将文件存储到指定的位置
        try {
            file.transferTo(new File(path, filename));

        } catch (IOException e) {
            e.printStackTrace();
            R.error("图片上传失败");
        }
        return R.success(filename);
    }

    /**
     * 图片下载接口
     * @param name
     * @param response
     * @throws Exception
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws Exception {
        //FileInputStream inputStream = new FileInputStream(new File(path + "\\" + name));
        FileInputStream inputStream = new FileInputStream(new File(path + File.separator + name));
        IoUtil.copy(inputStream, response.getOutputStream());
        inputStream.close();
    }


}
